package com.example.app.config;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.example.app.manager.TokenManager;
import com.example.app.page.LoginActivity;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class RetrofitClient {
    private static final String TAG = "RetrofitClient";
    private static final String BASE_URL = "http://10.234.32.109:7005";
    private static volatile RetrofitClient instance;
    private final Retrofit loginRetrofit;
    private final Retrofit authRetrofit;
    private final TokenManager tokenManager;

    // 私有构造方法（使用 Application Context）
    private RetrofitClient(Application application) {
        tokenManager = new TokenManager(application);

        // 初始化登录实例（不带 Token）
        loginRetrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(createLoginClient())
                .addConverterFactory(GsonConverterFactory.create())
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();

        // 初始化认证实例（带 Token）
        authRetrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(createAuthClient(application))
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    // 获取单例（确保线程安全）
    public static RetrofitClient getInstance(Application application) {
        if (instance == null) {
            synchronized (RetrofitClient.class) {
                if (instance == null) {
                    instance = new RetrofitClient(application);
                }
            }
        }
        return instance;
    }

    // 创建登录用的 OkHttpClient
    private OkHttpClient createLoginClient() {
        return new OkHttpClient.Builder()
                .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                .build();
    }

    // 创建带 Token 的 OkHttpClient
    private OkHttpClient createAuthClient(Context context) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .addInterceptor(chain -> {
                    // 添加 Token 到请求头
                    String token = tokenManager.getToken();
                    if (token == null) {
                        Log.w(TAG, "Token is null, aborting request");
                        throw new IllegalStateException("Token is required but not available");
                    }
                    Request request = chain.request().newBuilder()
                            .header("Authorization", "Bearer " + token)
                            .build();
                    return chain.proceed(request);
                })
                .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                .addInterceptor(create401Interceptor(context));

        return builder.build();
    }

    // 处理 401 错误的拦截器
    private Interceptor create401Interceptor(Context context) {
        return chain -> {
            Response response = chain.proceed(chain.request());
            if (response.code() == 401) {
                Log.d(TAG, "Token expired, redirecting to login");
                // 跳转登录页（通过 Intent.FLAG_ACTIVITY_NEW_TASK 避免 Context 类型问题）
                Intent intent = new Intent(context, LoginActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
                tokenManager.clearToken();
            }
            return response;
        };
    }

    // 获取服务接口实例
    public <T> T getLoginService(Class<T> service) {
        return loginRetrofit.create(service);
    }

    public <T> T getAuthService(Class<T> service) {
        return authRetrofit.create(service);
    }

    public TokenManager getTokenManager() {
        return tokenManager;
    }
}